﻿//This C# code file was released under the Ms-PL license
//http://www.opensource.org/licenses/ms-pl.html
//This script was originally intended for use with Microsoft Dynamics AX
//and maintained and distributed as a project on CodePlex
//http://dynamicsaxadmin.codeplex.com

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Activities;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Build.Workflow.Activities;
using System.IO;

namespace CodeCrib.AX2009.TFS
{
    [BuildActivity(HostEnvironmentOption.Agent)]
    public class DeployReferences : CodeActivity
    {
        public InArgument<string> ConfigurationFile { get; set; }
        [RequiredArgument]
        public InArgument<string> ReferencesFolder { get; set; }
        [RequiredArgument]
        public InArgument<string> ProbingFolder { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            string configurationFile = ConfigurationFile.Get(context);
            string sourcePath = ReferencesFolder.Get(context);
            string probingFolder = ProbingFolder.Get(context);

            context.TrackBuildMessage("Deploying references to client and server");

            if (Directory.Exists(sourcePath))
            {
                var serverConfig = Helper.GetServerConfig(configurationFile);

                string clientPath = Path.Combine(Path.GetDirectoryName(new Client.Client().ExecutablePath), probingFolder);
                string serverPath = Path.Combine(serverConfig.AlternateBinDirectory, probingFolder);

                if (!Directory.Exists(clientPath))
                {
                    Directory.CreateDirectory(clientPath);
                }
                if (!Directory.Exists(serverPath))
                {
                    Directory.CreateDirectory(serverPath);
                }

                IEnumerable<string> files = Directory.EnumerateFiles(sourcePath, "*");
                foreach (string file in files)
                {
                    File.Copy(file, Path.Combine(clientPath, Path.GetFileName(file)));
                    File.Copy(file, Path.Combine(serverPath, Path.GetFileName(file)));
                }
            }
            else
            {
                context.TrackBuildWarning(string.Format("Folder '{0}' containing reference files does not exist", sourcePath));
            }
        }
    }
}